package com.lb.activity.sys.service.impl;

import com.lb.activity.mapper.PermissionMapper;
import com.lb.activity.mapper.RolePermissionMapper;
import com.lb.activity.po.Permission;
import com.lb.activity.po.PermissionExample;
import com.lb.activity.po.RolePermission;
import com.lb.activity.po.Tree;
import com.lb.activity.sys.service.PermissionService;
import com.lb.activity.util.BuildTree;
import com.lb.activity.util.SnowflakeIdWorker;
import com.lb.activity.util.emumdata.DataEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 001030
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private PermissionMapper permissionMapper;

    @Resource
    private SnowflakeIdWorker idWorker;

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public Permission getPermission(Long permissionid) {
        return permissionMapper.selectByPrimaryKey(permissionid);
    }


    /**
     * 获取所有的菜单
     * @return
     */
    @Override
    public List<Permission> AllMeuns() {
        PermissionExample example=new PermissionExample();
        example.setOrderByClause(" sort asc");
        PermissionExample.Criteria  criteria= example.createCriteria();
        criteria.andStatusNotEqualTo(Integer.parseInt(DataEnum.DELETE_STATUS.getStatus()+""));
        return permissionMapper.selectByExample(example);
    }

    /**
     * 添加菜单
     * @param permission
     */
    @Override
    public void addMenu(Permission permission) {
        if(permission.getParentid()==null){
            permission.setParentid((long)0);
        }
        if(permission.getId()==null){
            permission.setId(idWorker.nextId());
            save(permission);
        }else{
            update(permission);
        }
    }

    /**
     *
     * @param permission
     * @return
     */
    @Override
    public List<Permission> getMenusByName(Permission permission) {
        PermissionExample example=new PermissionExample();
        PermissionExample.Criteria  criteria= example.createCriteria();
        criteria.andNameEqualTo(permission.getName());
        criteria.andStatusNotEqualTo(Integer.parseInt(DataEnum.DELETE_STATUS.getStatus()+""));
        if(permission.getId()!=null){
            criteria.andIdNotEqualTo(permission.getId());
        }
        return permissionMapper.selectByExample(example);
    }

    @Override
    public List<Permission> getMenusByPid(Long id) {
        PermissionExample example=new PermissionExample();
        PermissionExample.Criteria  criteria= example.createCriteria();
        criteria.andParentidEqualTo(id);
        criteria.andStatusNotEqualTo(Integer.parseInt(DataEnum.DELETE_STATUS.getStatus()+""));
        return permissionMapper.selectByExample(example);
    }

    @Override
    public void delete(Long id) {
        //删除之前，清除菜单和角色关系表,未做待续
        permissionMapper.deleteRolePermiss(id);
        Permission storeAdminPermission = getPermission(id);
        storeAdminPermission.setStatus(Integer.parseInt(DataEnum.DELETE_STATUS.getStatus()+""));
        this.update(storeAdminPermission);
    }

    @Override
    public List<Tree<Permission>> listMenuTree(Long userId) {
        List<Tree<Permission>> trees = new ArrayList<Tree<Permission>>();
        List<Permission> storeAdminPermissions= permissionMapper.listMenuByUserId(userId);
        for (Permission storeAdminPermission : storeAdminPermissions) {
            Tree<Permission> tree = new Tree<Permission>();
            tree.setId(storeAdminPermission.getId().toString());
            tree.setParentId(storeAdminPermission.getParentid().toString());
            tree.setText(storeAdminPermission.getName());
            Map<String, Object> attributes = new HashMap<String, Object>();
            attributes.put("url", storeAdminPermission.getUrl());
            attributes.put("icon", storeAdminPermission.getIcon());
            tree.setAttributes(attributes);
            trees.add(tree);
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        List<Tree<Permission>> list = BuildTree.buildList(trees, "0");
        return list;
    }

    @Override
    public Tree<Permission> getTree(Long id) {
        //查询所有的权限菜单
        List<Permission> storeAdminPermissions = getMeunsList();
        //获取该角色所拥有的权限caidan
        List<Long> menuIds = permissionMapper.listMenuIdByRoleId(id);
        List<Long> temp = menuIds;
        for (Permission menu : storeAdminPermissions) {
            if (temp!=null&&temp.size()>0&&temp.contains(menu.getParentid())) {
                menuIds.remove(menu.getParentid());
            }
        }
        List<Tree<Permission>> trees = new ArrayList<>();
        //List<StoreAdminPermission> StoreAdminPermissions = getMeunsList();
        for (Permission storeAdminPermission : storeAdminPermissions) {
            Tree<Permission> tree = new Tree<>();
            tree.setId(storeAdminPermission.getId().toString());
            tree.setParentId(storeAdminPermission.getParentid().toString());
            tree.setText(storeAdminPermission.getName());
            Map<String, Object> state = new HashMap<>(1);
            Long menuId = storeAdminPermission.getId();
            if (menuIds!=null&&menuIds.size()>0&&menuIds.contains(menuId)) {
                state.put("selected", true);
            } else {
                state.put("selected", false);
            }
            tree.setState(state);
            trees.add(tree);
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        Tree<Permission> t = BuildTree.build(trees);
        return t;
    }

    /**
     * 查询所有合法的菜单
     */
    @Override
    public List<Permission> getMeunsList() {
        PermissionExample example = new PermissionExample();
        example.setOrderByClause(" sort asc");
        PermissionExample.Criteria  criteria= example.createCriteria();
        criteria.andStatusEqualTo(Integer.parseInt(DataEnum.INSERT_STATUS.getStatus()+""));
        return permissionMapper.selectByExample(example);
    }

    @Override
    public void updateRoleAndmenuIds(Long roleId, List<String> menuIds) {
        permissionMapper.removeByRoleId(roleId);
        List<RolePermission> storeRolePermissions = new ArrayList<>();
        for (String  menuId: menuIds) {
            RolePermission storeRolePermission= new RolePermission();
            storeRolePermission.setId(idWorker.nextId());
            storeRolePermission.setRoleid(roleId);
            storeRolePermission.setPermissionid(Long.valueOf(menuId));
            storeRolePermission.setStatus(Integer.parseInt(DataEnum.INSERT_STATUS.getStatus()+""));
            storeRolePermissions.add(storeRolePermission);
        }
        if (storeRolePermissions.size() > 0) {
            rolePermissionMapper.batchSave(storeRolePermissions);
        }
    }

    /**
     * 更新
     * @param storeAdminPermission
     */
    private void update(Permission storeAdminPermission) {
        permissionMapper.updateByPrimaryKeySelective(storeAdminPermission);
    }

    /**
     * 添加
     * @param storeAdminPermission
     */
    private void save(Permission storeAdminPermission) {
        permissionMapper.insertSelective(storeAdminPermission);
    }
}
